package com.my.vote.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.my.utils.CalendarUtil;
import com.my.vote.entity.VoteArea;
import com.my.vote.entity.VoteOption;
import com.my.vote.entity.VoteQuestion;
import com.my.vote.entity.VoteSubject;
import com.my.vote.repository.VoteAreaRepository;
import com.my.vote.repository.VoteOptionRepository;
import com.my.vote.repository.VoteQuestionRepository;
import com.my.vote.repository.VoteSubjectRepository;
import com.my.vote.repository.param.SubjectQuery;
import com.my.vote.repository.param.VoteAreaSVO;
import com.my.vote.repository.param.VoteOptionSVO;
import com.my.vote.repository.param.VoteQuestionSVO;
import com.my.vote.repository.param.VoteSubjectSVO;
import com.my.vote.repository.response.SubjectSavedResponse;
import com.my.xq.repository.DoorplateRepository;
import com.sskj.core.annotation.ControllerLogExeTime;

@RestController
@RequestMapping("/vote/subject")
public class VoteSubjectServiceImpl {

	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	VoteSubjectRepository voteSubjectRepository;

	@Autowired
	VoteQuestionRepository voteQuestionRepository;

	@Autowired
	VoteOptionRepository voteOptionRepository;

	@Autowired
	VoteAreaRepository voteAreaRepository;

	@Autowired
	DoorplateRepository doorplateRepository;

	@CrossOrigin(origins = "*", maxAge = 3600)
	@RequestMapping(value = "/id", method = { RequestMethod.GET })
	@ControllerLogExeTime(description = "查询全部")
	public VoteSubjectSVO findSubjectById(String id) {
		logger.debug("投票主题查询开始");
		VoteSubjectSVO result = new VoteSubjectSVO();
		VoteSubject vs = voteSubjectRepository.findOne(id);
		if (vs != null) {
			result.setCreatorId(vs.getCreatorId());
			result.setDescription(vs.getDescription());
			result.setEndTime(CalendarUtil.DateToString(vs.getEndTime(), "yyyy/MM/dd HH:mm"));
			result.setId(vs.getId());
			result.setStatus(vs.getStatus());
			result.setTitle(vs.getTitle());
			result.setVoteCount(vs.getVoteCount());
		} else {
			result.setEndTime(CalendarUtil.DateToString(new Date(), "yyyy/MM/dd HH:mm"));
		}
		return result;
	};

	@CrossOrigin(origins = "*", maxAge = 3600)
	@RequestMapping(value = "/all", method = { RequestMethod.GET })
	@ControllerLogExeTime(description = "查询全部")
	public List<VoteSubject> findAllSubject() {
		logger.debug("投票主题查询开始");
		return voteSubjectRepository.findAllOrderCreateTime();
	};

	@CrossOrigin(origins = "*", maxAge = 3600)
	@RequestMapping(value = "/all/by/creator", method = { RequestMethod.GET })
	@ControllerLogExeTime(description = "根据投票创建人查询")
	public List<VoteSubject> findAllByCreator(SubjectQuery params) {
		logger.debug("投票主题查询开始");
		return voteSubjectRepository.findAllByCreator(params.getCreatorId());
	};

	@CrossOrigin(origins = "*", maxAge = 3600)
	@RequestMapping(value = "/all/by/title", method = { RequestMethod.GET })
	@ControllerLogExeTime(description = "根据投票标题查询")
	public List<VoteSubject> findAllByTile(SubjectQuery params) {
		logger.debug("投票主题查询开始");
		return voteSubjectRepository.findAllByTitle(params.getTitle());
	};

	@CrossOrigin(origins = "*", maxAge = 3600)
	@RequestMapping(value = "/questionnaire", method = { RequestMethod.GET })
	@ControllerLogExeTime(description = "根据问卷ID查询问卷调查内容（包括所有题目和选项）")
	public VoteSubjectSVO findQuestionnaire(String subjectId) {
		VoteSubjectSVO vsSVO = new VoteSubjectSVO();
		VoteSubject vs = voteSubjectRepository.findOne(subjectId);
		if (vs != null) {
			vsSVO = new VoteSubjectSVO();
			vsSVO.setCreatorId(vs.getCreatorId());
			vsSVO.setDescription(vs.getDescription());
			vsSVO.setEndTime(CalendarUtil.DateToString(vs.getEndTime(), "yyyy/MM/dd HH:mm"));
			vsSVO.setId(vs.getId());
			vsSVO.setStatus(vs.getStatus());
			vsSVO.setTitle(vs.getTitle());
			vsSVO.setVoteCount(vs.getVoteCount());
			List<VoteQuestion> vqs = voteQuestionRepository.findAllBySubjectId(subjectId);
			if (vqs != null && vqs.size() > 0) {
				List<VoteQuestionSVO> vqSVOs = new ArrayList<VoteQuestionSVO>();
				for (VoteQuestion vq : vqs) {
					VoteQuestionSVO vqSvo = new VoteQuestionSVO();
					vqSvo.setDescription(vq.getDescription());
					vqSvo.setId(vq.getId());
					vqSvo.setOrderNum(vq.getOrderNum());
					vqSvo.setSubjectId(vq.getSubjectId());
					vqSvo.setTitle(vq.getTitle());
					vqSvo.setType(vq.getType());
					List<VoteOption> vos = voteOptionRepository.findAllByQuestionId(vq.getId());
					if (vos != null && vos.size() > 0) {
						List<VoteOptionSVO> voSVOs = new ArrayList<VoteOptionSVO>();
						for (VoteOption vo : vos) {
							VoteOptionSVO voSvo = new VoteOptionSVO();
							voSvo.setId(vo.getId());
							voSvo.setOptionDesc(vo.getOptionDesc());
							voSvo.setQuestionId(vo.getQuestionId());
							voSvo.setOrderNum(vo.getOrderNum());
							voSVOs.add(voSvo);
						}
						vqSvo.setOptions(voSVOs);
					}
					vqSVOs.add(vqSvo);
				}
				vsSVO.setQuestions(vqSVOs);
			}
			List<VoteAreaSVO> areas = new ArrayList<VoteAreaSVO>();
			List<VoteArea> vas = voteAreaRepository.findAllBySubjectId(subjectId);
			if (vas != null && vas.size() > 0) {
				for (VoteArea va : vas) {
					VoteAreaSVO vaSvo = new VoteAreaSVO();
					vaSvo.setArea(va.getArea());
					vaSvo.setSubjectId(va.getSubjectId());
					areas.add(vaSvo);
				}
			}
			vsSVO.setAreas(areas);
		}
		return vsSVO;
	}

	@CrossOrigin(origins = "*", maxAge = 3600)
	@RequestMapping(value = "/all/my/voted", method = { RequestMethod.GET })
	@ControllerLogExeTime(description = "根据投票人ID查询参与过的")
	public List<VoteSubject> findAllMyVoted(SubjectQuery params) {
		logger.debug("投票主题查询开始");
		return voteSubjectRepository.findAllMyVoted(params.getVoterId());
	};

	@CrossOrigin(origins = "*", maxAge = 3600)
	@RequestMapping(value = "/save", method = { RequestMethod.POST })
	@ControllerLogExeTime(description = "保存投票主题")
	public SubjectSavedResponse save(String param) {

		try {
			VoteSubjectSVO params = JSON.parseObject(param, VoteSubjectSVO.class);
			logger.debug(JSON.toJSONString(params));
			VoteSubject vsSave;
			if (StringUtils.isNotEmpty(params.getId())) {
				vsSave = voteSubjectRepository.findOne(params.getId());
				if (vsSave == null) {
					vsSave = new VoteSubject();
				}
			} else {
				vsSave = new VoteSubject();
			}
			vsSave.setDelFlag(false);
			vsSave.setTitle(params.getTitle());
			vsSave.setDescription(params.getDescription());
			vsSave.setCreatorId(params.getCreatorId());
			vsSave.setEndTime(CalendarUtil.stringToDate(params.getEndTime(), "yyyy/MM/dd HH:mm"));
			vsSave.setStatus(params.getStatus());
			vsSave.setVoteCount(params.getVoteCount());
			VoteSubject vsSaved = voteSubjectRepository.save(vsSave);
			if (vsSaved != null && StringUtils.isNotEmpty(vsSaved.getId())) {
				List<String> courtIds = doorplateRepository.findCourtIdByProprietorId(vsSaved.getCreatorId());
				voteAreaRepository.deleteAllBySubjectId(vsSaved.getId());
				if (courtIds != null) {
					for (String courtId : courtIds) {
						VoteArea vaSave = new VoteArea();
						vaSave.setArea(courtId);
						vaSave.setSubjectId(vsSaved.getId());
						voteAreaRepository.save(vaSave);
					}
				}
				// 更新投票问题
				if (params.getQuestions() != null) {
					for (VoteQuestionSVO vqParam : params.getQuestions()) {
						VoteQuestion vq = null;
						if (StringUtils.isNotEmpty(vqParam.getId())) {
							vq = voteQuestionRepository.findOne(vqParam.getId());
						}
						if (vq == null) {
							vq = new VoteQuestion();
						}
						vq.setDelFlag(false);
						vq.setCreatorId(params.getCreatorId());
						vq.setDescription(vqParam.getDescription());
						vq.setSubjectId(vsSaved.getId());
						vq.setTitle(vqParam.getTitle());
						vq.setType(vqParam.getType());
						vq.setOrderNum(vqParam.getOrderNum());
						VoteQuestion vqSaved = voteQuestionRepository.save(vq);
						if (vqSaved != null && StringUtils.isNotEmpty(vqSaved.getId())) {
							if (vqParam.getOptions() != null) {
								for (VoteOptionSVO voParam : vqParam.getOptions()) {
									VoteOption vo = null;
									if (StringUtils.isNotEmpty(voParam.getId())) {
										vo = voteOptionRepository.findOne(voParam.getId());
									}
									if (vo == null) {
										vo = new VoteOption();
									}
									vo.setOptionDesc(voParam.getOptionDesc());
									vo.setQuestionId(vqSaved.getId());
									vo.setSubjectId(vqSaved.getSubjectId());
									vo.setDelFlag(false);
									vo.setOrderNum(voParam.getOrderNum());
									voteOptionRepository.save(vo);
								}
							}
						}
					}
				}
				return new SubjectSavedResponse(true, vsSaved.getId());
			} else {
				return new SubjectSavedResponse(false, null);
			}
		} catch (Exception e) {
			return new SubjectSavedResponse(false, null);
		}
	}

}
